using Avalonia.Interactivity;

namespace KinonekoSoftware.Foundation.UI.Controls.Selectors
{
    public class MultipleSelectionStatic : AvaloniaObject
    {
        public static readonly AttachedProperty<bool> EnableMultipleSelectionProperty;

        static MultipleSelectionStatic()
        {
            EnableMultipleSelectionProperty = AvaloniaProperty.RegisterAttached<MultipleSelectionStatic, ForestListBoxBase, bool>("EnableMultipleSelection");
            EnableMultipleSelectionProperty.Changed.Subscribe(args =>
            {
                if (args.Sender is not ForestListBoxBase d)
                {
                    return;
                }

                if (args.GetNewValue<bool>())
                {
                    Subscribe(d);
                }
                else
                {
                    Unsubscribe(d);
                }
                
            });
        }

        private static void Subscribe(SelectingItemsControl d)
        {
            
            d.Loaded           += OnLoaded;
            d.Unloaded         += OnUnloaded;
            d.SelectionChanged += OnSelectionChanged;
        }
        
        private static void Unsubscribe(SelectingItemsControl d)
        {
            
            d.Loaded           -= OnLoaded;
            d.Unloaded         -= OnUnloaded;
            d.SelectionChanged -= OnSelectionChanged;
        }
        
        private static void OnUnloaded(object sender, RoutedEventArgs e)
        {
            if (sender is not ForestListBoxBase d)
            {
                return;
            }
            
            Unsubscribe(d);
        }
        
        private static void OnLoaded(object sender, RoutedEventArgs e)
        {
            if (sender is not ForestListBoxBase { DataContext: IMultiplePurposeSelector vm } d)
            {
                return;
            }

            d.SelectionMode = vm.IsMultipleSelection ? SelectionMode.Multiple : SelectionMode.Single;
        }
        
        private static void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (sender is not ForestListBoxBase { DataContext: IMultiplePurposeSelector vm } d)
            {
                return;
            }

            if (vm.IsMultipleSelection)
            {
                vm.SelectedItems = d.SelectedItems;
            }
            else
            {
                vm.SelectedItem = d.SelectedItem;
            }
        }

        public static bool GetEnableMultipleSelection(ForestListBoxBase d)
        {
            return d.GetValue(EnableMultipleSelectionProperty);
        }
        
        
        public static void SetEnableMultipleSelection(ForestListBoxBase obj, bool value)
        {
            obj.SetValue(EnableMultipleSelectionProperty, value);
        }
    }
}